package services

import (
	"errors"
	"fmt"
	"github.com/xuri/excelize/v2"
	"time"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

func ProductInventoryCreateExcel(params *models.ErpInventoryQueryParam) (string, error) {

	params.Limit = 200000
	params.Offset = 0
	data, total := models.ErpInventoryPageList(params)
	if total <= 0 {
		return "", errors.New("没有找到库存数据")
	}

	xlsxData := make([]map[string]string, 0)

	xlsxHeader := map[string]string{"A1": "名称", "B1": "屈光度", "C1": "散光度", "D1": "销售价", "E1": "类别", "F1": "品牌", "G1": "库存", "I1": "更新时间", "J1": "更新人", "K1": "型号", "L1": "色号", "M1": "编码", "N1":"供应商", "O1":"实盘数"}

	xlsxData = append(xlsxData, xlsxHeader)

	var i int64 = 1
	var inventory int64
	for _, v := range data { //处理数据
		i++
		d := make(map[string]string)
		d[fmt.Sprintf("A%d", i)] = v.ProductName //产品名称
		d[fmt.Sprintf("B%d", i)] = v.Diopter
		d[fmt.Sprintf("C%d", i)] = v.Astigmatism
		d[fmt.Sprintf("D%d", i)] = fmt.Sprintf("%0.2f", "0")
		d[fmt.Sprintf("E%d", i)] = ""
		d[fmt.Sprintf("F%d", i)] = v.Products.Brand.BrandName
		d[fmt.Sprintf("G%d", i)] = fmt.Sprintf("%d", v.Inventory)
		//d[fmt.Sprintf("H%d", i)] = v.Warehouse.WarehouseName
		d[fmt.Sprintf("I%d", i)] = utils.GetDateMH(v.UpdatedAt)
		d[fmt.Sprintf("J%d", i)] = v.UpdatedBy
		d[fmt.Sprintf("K%d", i)] = v.ModelNumber
		d[fmt.Sprintf("L%d", i)] = v.ColourNumber
		d[fmt.Sprintf("M%d", i)] = v.Products.Number
		d[fmt.Sprintf("N%d", i)] = v.Products.Suppliers.Name
		d[fmt.Sprintf("O%d", i)] = "0"
		inventory = inventory + v.Inventory;

		xlsxData = append(xlsxData, d)
	}
	//合计行
	totals := make(map[string]string)
	i++
	totals[fmt.Sprintf("A%d", i)] = "合计" //产品名称
	totals[fmt.Sprintf("B%d", i)] = ""
	totals[fmt.Sprintf("C%d", i)] = ""
	totals[fmt.Sprintf("D%d", i)] = ""
	totals[fmt.Sprintf("E%d", i)] = ""
	totals[fmt.Sprintf("F%d", i)] = ""
	totals[fmt.Sprintf("G%d", i)] = fmt.Sprintf("%d", inventory)
	totals[fmt.Sprintf("I%d", i)] = ""
	totals[fmt.Sprintf("J%d", i)] = ""
	totals[fmt.Sprintf("K%d", i)] = ""
	totals[fmt.Sprintf("L%d", i)] = ""
	totals[fmt.Sprintf("M%d", i)] = ""
	totals[fmt.Sprintf("N%d", i)] = ""
	totals[fmt.Sprintf("O%d", i)] = "0"
	xlsxData = append(xlsxData, totals)

	xlsx := excelize.NewFile() //创建表格句柄

	for _, val := range xlsxData { //生成表格行
		if len(val) > 0 {
			for k, v := range val {
				if len(v) > 0 && len(k) > 0 {
					xlsx.SetCellValue("Sheet1", k, v)
				}
			}
		}
	}

	fileName := fmt.Sprintf("./static/download/KCPD-%s%d.xlsx", time.Now().Format("20060102"), models.CurLoginUserInfo.Id)

	err := xlsx.SaveAs(fileName)

	if err != nil {
		return "", err
	}
	return "/" + fileName, nil
}
